import uuid
from datetime import datetime
from typing import Any

from fastapi import APIRouter, HTTPException
from sqlmodel import func, select

from app.api.deps import CurrentUser, SessionDep
from app.models.debate_models import (
    DebateSession,
    DebateSessionCreate,
    DebateSessionUpdate,
    DebateSessionPublic,
    DebateSessionsPublic, DebateTurnPublic, DebateTurnCreate, DebateTurn, ReportPublic, ReportCreate, Report,
    DebateHistoryResponse, DebateTurnsResponse,
)

router = APIRouter(prefix="/debates", tags=["debates"])

@router.post("/turns", response_model=DebateTurnPublic)
def create_debate_turn(
    *, session: SessionDep, current_user: CurrentUser, item_in: DebateTurnCreate
) -> Any:
    turn = DebateTurn.model_validate(item_in)
    session.add(turn)
    session.commit()
    session.refresh(turn)
    return turn

@router.get("/turns/{session_id}", response_model=list[DebateTurnPublic])
def read_turns_by_session(session: SessionDep, session_id: uuid.UUID) -> Any:
    turns = session.exec(
        select(DebateTurn).where(DebateTurn.session_id == session_id).order_by(DebateTurn.turn_index)
    ).all()
    return turns

@router.post("/reports", response_model=ReportPublic)
def create_report(
    *, session: SessionDep, current_user: CurrentUser, item_in: ReportCreate
) -> Any:
    report = Report.model_validate(item_in, update={"user_id": current_user.id})
    session.add(report)
    session.commit()
    session.refresh(report)
    return report

@router.get("/reports/{session_id}", response_model=ReportPublic)
def read_report_by_session(session: SessionDep, session_id: uuid.UUID) -> Any:
    report = session.exec(select(Report).where(Report.session_id == session_id)).first()
    if not report:
        raise HTTPException(status_code=404, detail="Report not found")
    return report

@router.get("/history", response_model=DebateHistoryResponse)
def get_debate_history(
        session: SessionDep,
        current_user: CurrentUser,
        skip: int = 0,
        limit: int = 100
) -> Any:
    """获取用户的辩论历史记录"""
    if current_user.is_superuser:
        count = session.exec(select(func.count()).select_from(DebateSession)).one()
        items = session.exec(
            select(DebateSession)
            .order_by(DebateSession.created_at.desc())
            .offset(skip)
            .limit(limit)
        ).all()
    else:
        count = session.exec(
            select(func.count())
            .select_from(DebateSession)
            .where(DebateSession.user_id == current_user.id)
        ).one()
        items = session.exec(
            select(DebateSession)
            .where(DebateSession.user_id == current_user.id)
            .order_by(DebateSession.created_at.desc())
            .offset(skip)
            .limit(limit)
        ).all()
        print(items)
        print(DebateHistoryResponse(data=items, count=count))
    return DebateHistoryResponse(data=items, count=count)


@router.get("/{session_id}/messages", response_model=DebateTurnsResponse)
def get_session_messages(
        session: SessionDep,
        current_user: CurrentUser,
        session_id: uuid.UUID
) -> Any:
    """获取特定辩论会话的所有消息"""
    # 首先检查会话是否存在且属于当前用户
    debate = session.get(DebateSession, session_id)
    if not debate:
        raise HTTPException(status_code=404, detail="Debate session not found")

    if not current_user.is_superuser and debate.user_id != current_user.id:
        raise HTTPException(status_code=403, detail="Not enough permissions")

    # 获取会话的所有消息
    turns = session.exec(
        select(DebateTurn)
        .where(DebateTurn.session_id == session_id)
        .order_by(DebateTurn.turn_index)
    ).all()

    count = len(turns)
    return DebateTurnsResponse(data=turns, count=count)


@router.get("/", response_model=DebateSessionsPublic)
def read_debate_sessions(
    session: SessionDep, current_user: CurrentUser, skip: int = 0, limit: int = 100
) -> Any:
    if current_user.is_superuser:
        count = session.exec(select(func.count()).select_from(DebateSession)).one()
        items = session.exec(select(DebateSession).offset(skip).limit(limit)).all()
    else:
        count = session.exec(
            select(func.count()).select_from(DebateSession).where(DebateSession.user_id == current_user.id)
        ).one()
        items = session.exec(
            select(DebateSession)
            .where(DebateSession.user_id == current_user.id)
            .offset(skip)
            .limit(limit)
        ).all()
    return DebateSessionsPublic(data=items, count=count)


@router.get("/{id}", response_model=DebateSessionPublic)
def read_debate_session(session: SessionDep, current_user: CurrentUser, id: uuid.UUID) -> Any:
    debate = session.get(DebateSession, id)
    if not debate:
        raise HTTPException(status_code=404, detail="Debate session not found")
    if not current_user.is_superuser and debate.user_id != current_user.id:
        raise HTTPException(status_code=403, detail="Not enough permissions")
    return debate


@router.post("/", response_model=DebateSessionPublic)
def create_debate_session(
    *, session: SessionDep, current_user: CurrentUser, item_in: DebateSessionCreate
) -> Any:
    debate = DebateSession.model_validate(item_in, update={"user_id": current_user.id})
    session.add(debate)
    session.commit()
    session.refresh(debate)
    return debate


@router.put("/{id}", response_model=DebateSessionPublic)
def update_debate_session(
    *, session: SessionDep, current_user: CurrentUser, id: uuid.UUID, item_in: DebateSessionUpdate
) -> Any:
    debate = session.get(DebateSession, id)
    if not debate:
        raise HTTPException(status_code=404, detail="Debate session not found")
    if debate.user_id != current_user.id:
        raise HTTPException(status_code=403, detail="Not enough permissions")
    update_dict = item_in.model_dump(exclude_unset=True)
    debate.sqlmodel_update(update_dict)
    session.add(debate)
    session.commit()
    session.refresh(debate)
    return debate


@router.delete("/{id}")
def delete_debate_session(
    session: SessionDep, current_user: CurrentUser, id: uuid.UUID
) -> dict:
    debate = session.get(DebateSession, id)
    if not debate:
        raise HTTPException(status_code=404, detail="Debate session not found")
    if not current_user.is_superuser and debate.user_id != current_user.id:
        raise HTTPException(status_code=403, detail="Not enough permissions")
    session.delete(debate)
    session.commit()
    return {"message": "Debate session deleted successfully"}